/******************************************************************************
	This file is a part of the Snapshot Bioinformatics Project

	Copyright (C) 2012-2013 Jarom Schow

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/

#include "EFetch.h"

#include <QtCore/QUrl>
#include <QtCore/QUrlQuery>
#include <QtCore/QFile>

#include "OutputParser.h"

using namespace Bio;

const QString	c_efetchUrl = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi";

///////////////////////////////////////////////////////////////////////////////
//	EFetch
///////////////////////////////////////////////////////////////////////////////

/**
	@class EFetch
	@brief Implementation of the Entrez 'Fetch' function.

	Provides an interface to the NCBI Entrez 'Fetch' function.

	See http://www.ncbi.nlm.nih.gov/books/NBK25499/ for details on
	the Entrez Fetch utility.
**/

/**
	Default Constructor. Creates a new Fetch operation.
**/
EFetch::EFetch() : m_queryKey( -1 ), m_retStart( -1 ), m_retMax( -1 ),
		m_seqStart( -1 ), m_seqStop( -1 ), m_complexity( -1 ), m_strand( -1 )
{
}

/**
	General Constructor. Creates a new Fetch operation for a single ID.
	@param	db	The name of the NCBI database to fetch records from.
	@param	id	The ID of the data item to retrieve.
**/
EFetch::EFetch( const QString &db, const QString &id ) : m_db( db ),
	m_queryKey( -1 ), m_retStart( -1 ), m_retMax( -1 ), m_seqStart( -1 ),
	m_seqStop( -1 ), m_complexity( -1 ), m_strand( -1 )
{
	m_ids.append( id );
}

/**
	General Constructor. Creates a new Fetch operation for a list of IDs.
	@param	db	The name of the NCBI database to fetch records from.
	@param	ids	The list of IDs of the data items to retrieve.
**/
EFetch::EFetch( const QString &db, const QStringList &ids ) : m_db( db ),
	m_ids( ids ), m_queryKey( -1 ), m_retStart( -1 ), m_retMax( -1 ),
	m_seqStart( -1 ), m_seqStop( -1 ), m_complexity( -1 ), m_strand( -1 )
{
}

/**
	General Constructor. Creates a new Fetch operation to retrieve results
	from a saved query.
	@param	db			The name of the NCBI database to fetch records from.
	@param	queryKey	The key for the saved query.
	@param	webEnv		The web environment string for the saved query.
**/
EFetch::EFetch( const QString &db, int queryKey, const QString &webEnv ) : m_db( db ),
	m_queryKey( queryKey ), m_webEnv( webEnv ), m_retStart( -1 ), m_retMax( -1 ),
	m_seqStart( -1 ), m_seqStop( -1 ), m_complexity( -1 ), m_strand( -1 )
{
}

/**
	Destructor.
**/
EFetch::~EFetch()
{
}

/**
	Executes the fetch operation.
	@return	true on success, otherwise false.
**/
bool EFetch::exec()
{
	QUrl		url( c_efetchUrl );
	QUrlQuery	urlQuery;

	if( m_db.isEmpty() ){
		error( "No database specified for EFetch." );
		return false;
	}

	urlQuery.addQueryItem( "db", m_db );
	
	// url.addQueryItem( "retmode", m_retmode );
	// url.addQueryItem( "rettype", m_rettype );

	if( m_retStart >= 0 )
		urlQuery.addQueryItem( "retstart", QString::number( m_retStart ) );

	if( m_retMax >= 0 )
		urlQuery.addQueryItem( "retmax", QString::number( m_retMax ) );

	if( m_strand >= 0 )
		urlQuery.addQueryItem( "strand", QString::number( m_strand ) );

	if( m_seqStart >= 0 )
		urlQuery.addQueryItem( "seq_start", QString::number( m_seqStart ) );

	if( m_seqStop >= 0 )
		urlQuery.addQueryItem( "seq_stop", QString::number( m_seqStop ) );

	if( m_complexity >= 0 )
		urlQuery.addQueryItem( "complexity", QString::number( m_complexity ) );

	QFile			output( "EFetch.txt" );
	OutputParser	parser( output );

	if( m_queryKey < 0 ){
		if( m_ids.isEmpty() ){
			error( "Must specify IDs or history settings for EFetch." );
			return false;
		}

		if( m_ids.count() > 200 )
			return execPost( url, m_ids, parser );
		
		urlQuery.addQueryItem( "id", m_ids.join( "," ) );
	}
	else {
		if( m_webEnv.isEmpty() ){
			error( "Invalid WebEnv specified for EFetch." );
			return false;
		}

		urlQuery.addQueryItem( "query_key", QString::number( m_queryKey ) );
		urlQuery.addQueryItem( "WebEnv", m_webEnv );
	}

	url.setQuery( urlQuery );

	return execGet( url, parser );
}

/**
	Sets the name of the database for the fetch operation if one was not supplied 
	in the constructor.
	@param	db	The name of the NCBI database to fetch records from.
**/
void EFetch::setDatabase( const QString &db )
{
	m_db = db;
}

/**
	Get the name of the database used by this fetch operation.
	@return The name of the NCBI database to fetch records from.
**/
QString EFetch::getDatabase() const
{
	return m_db;
}

/**
	Add the identifier for a data record to retrieve.
	@param	id	The ID of a data record to retrieve from the NCBI database.
**/
void EFetch::addID( const QString &id )
{
	m_ids.append( id );
}

/**
	Sets the list of identifiers of data records to retrieve.
	@param	ids	The list of IDs of data records to retrieve from the NCBI database.
**/
void EFetch::setIDs( const QStringList &ids )
{
	m_ids = ids;
}

/**
	Get the list of IDs of data records that will be retrieved by this operation.
	@return	The list of IDs for this fetch operation.
**/
QStringList EFetch::getIDs() const
{
	return m_ids;
}

/**
	Sets the history value for a fetch operation using a stored query.
	@param	queryKey	The key for the saved query.
	@param	webEnv		The web environment string for the saved query.
**/
void EFetch::setHistory( int queryKey, const QString &webEnv )
{
	m_queryKey = queryKey;
	m_webEnv = webEnv;
}

/**
	Get the query key for this fetch operation if any.
	@return	The query key for this operation, or -1 is none is set.
**/
int EFetch::getQueryKey() const
{
	return m_queryKey;
}

/**
	Get the web environment string for this operation if any.
	@return The web environment string for this fetch operation, or an empty 
			string if none is set.
**/
QString EFetch::getWebEnv() const
{
	return m_webEnv;
}

/**
	Set the index of the first item to retrieve for this fetch operation.
	@param	num	The index of the first record to fetch.
**/
void EFetch::setRetStart( int num )
{
	m_retStart = num;
}

/**
	Get the index of the first item to retrieve for this fetch operation.
	@return	The index of the first record that will be fetched, or -1 if not set.
**/
int EFetch::getRetStart() const
{
	return m_retStart;
}

/**
	Set the maximum number of items to retrieve for the fetch operation.
	@param	num	The maximum number of records to fetch.
**/
void EFetch::setRetMax( int num )
{
	m_retMax = num;
}

/**
	Get the maximum number of items to retrieve for this fetch operation.
	@return	The maximum number of records to fetch, or -1 if not set.
**/
int EFetch::getRetMax() const
{
	return m_retMax;
}

/**
	Set the strand to be retrieved for DNA records, 1 for plus strand, or 2 for minus strand.
	@param	num	The strand to retrieve.
**/
void EFetch::setStrand( int num )
{
	m_strand = num;
}

/**
	Get the strand to retrieve for this fetch operation.
	@return	1 for plus strand, or 2 for minus strand, or -1 if not set.
**/
int EFetch::getStrand() const
{
	return m_strand;
}

/**
	Set the index of the first sequence base to retrieve, with 1 for the first base of the
	sequence.
	@param	num	The index of the first base of the sequence to retrieve.
**/
void EFetch::setSeqStart( int num )
{
	m_seqStart = num;
}

/**
	Get the index of the first sequence base to retrieve for this fetch operation.
	@return	The index of the first sequence base to retrieve, or -1 if not set.
**/
int EFetch::getSeqStart() const
{
	return m_seqStart;
}

/**
	Set the index of the last sequence base to retrieve, with 1 for the first base of the
	sequence.
	@param	num	The index of the last base of the sequence to retrieve.
**/
void EFetch::setSeqStop( int num )
{
	m_seqStop = num;
}

/**
	Get the index of the last sequence base to retrieve for this fetch operation.
	@return	The index of the last sequence base to retrieve, or -1 if not set.
**/
int EFetch::getSeqStop() const
{
	return m_seqStop;
}

/**
	Set the complexity of the data content to fetch.
	@param	The data complexity value for this fetch operation.
**/
void EFetch::setComplexity( int num )
{
	m_complexity = num;
}

/**
	Get the data complexity value for this fetch operation.
	@return	The data complexity value, or -1 if not set.
**/
int EFetch::getComplexity() const
{
	return m_complexity;
}
